/*
 *  This file is part of Bracket Properties
 *  Copyright 2011 David R. Smith
 *
 */
package org.dave.bracket.properties;

import org.dave.bracket.properties.big.Line;
import org.dave.bracket.properties.big.LineScanner;
/**
 * Use the line scanner to load a Properties implementation
 * 
 * This class does not use PropertiesToken, it is intended for low memory situations
 * or for large properties files, where it ought to perform a bit better.
 * 
 * @author Dave
 *
 */
public class PropertiesParser2 {

	final LineScanner scanner;
	final Properties props;
	
	public PropertiesParser2(LineScanner scanner) {
		this.scanner=scanner;
		this.props = new PropertiesImpl();
	}
	
	public PropertiesParser2(LineScanner scanner, Properties props) {
		this.scanner=scanner;
		this.props = props;
	}
	
	public void parse(){
		Line line = null;
		String key = null;
		ValueModel model = new ValueModel();
		boolean hasContinuation=false;
		while((line =scanner.line())!=null){
			if(hasContinuation){
				model.addValue(line.logicalLineContents());
				if(line.hasContinuation()){
					continue;
				}else{
					hasContinuation=false;
				}
			}
			if(line.isEmptyLine())continue;
			if(line.isPrivateComment())continue;
			if(line.isCommentLine()){
				if(key !=null){
					props.getPropertyMap().put(key, model);
					key=null;
					model=new ValueModel();
				}
				model.addComment(line.commentContents());
				continue;
			}else if(line.isNaturalLine()){
				if(key !=null){
					props.getPropertyMap().put(key, model);
					key=null;
					model=new ValueModel();
				}
				String [] parts = line.naturalLineContents();
				key = parts[0];
				model.setSeparator(parts[1].charAt(0));
				hasContinuation=line.hasContinuation();
				model.addValue(parts[2]);
				
			}
		}
		// last one
		if(key !=null){
			props.getPropertyMap().put(key, model);
		}
	}
	
	public Properties getProperties() {
		return props;
	}

}
